package com.zdy.im.tio.command.handler;

import com.sixeco.framework.common.api.ApiDoc;
import com.sixeco.framework.common.enums.SysResultCodeEnum;
import com.sixeco.framework.http.JsonParse;
import com.sixeco.framework.http.exception.SystemRuntimeException;
import com.zdy.im.common.exception.ImException;
import com.zdy.im.core.ICommand;
import com.zdy.im.tio.command.AbstractCommandHandler;
import com.zdy.im.tio.command.Command;

import com.zdy.im.tio.packets.LoginRequestVo;
import com.zdy.im.tio.packets.LoginResponseVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.intf.Packet;
import org.tio.http.common.HttpRequest;
import org.tio.server.ServerChannelContext;
import java.util.List;
import java.util.Map;


/**
 * 登录消息命令处理器
 * @Author 作者 : zdy
 * @CreateDate 创建时间: 2021-02-30
 */
@Component
@ApiDoc(module = "WebSocket 项目文档",group = "SOCKET-GROUP")
public class LoginRequestHandler extends AbstractCommandHandler {

	private static Logger logger = LoggerFactory.getLogger(LoginRequestHandler.class);



	@Override
	public ICommand command() {
		return Command.COMMAND_LOGIN_REQ;
	}


	@ApiDoc(
			cmd = "5",methodType = "ws",
			value = "用户登录协议 cmd=5",
			request = LoginRequestVo.class,
			response = LoginResponseVo.class
	)
	@Override
	public Packet handler(Packet packet, ChannelContext channelContext) throws ImException {
		try {
			ServerChannelContext imServerChannelContext = (ServerChannelContext)channelContext;
			HttpRequest httpRequest = (HttpRequest)packet;
			Map map = httpRequest.getParams();
			LoginRequestVo loginRequestVo = JsonParse.parseFrom(map, LoginRequestVo.class);
			if(loginRequestVo == null){
//				LoginResponseVo loginResponseVo = LoginResponseVo.failed("登陆失败");
//				return this.converterWsResponse(loginResponseVo);
			}

			String userId = loginRequestVo.getUserIds();
			List<Long> groupList = loginRequestVo.getUserGroupList();
			String token = loginRequestVo.getToken();
			Tio.bindUser(imServerChannelContext,userId);
			Tio.bindToken(imServerChannelContext,token);
			if (null != groupList){
				groupList.forEach( groupName ->{
					Tio.bindGroup(imServerChannelContext,String.valueOf(groupName));
				} );

			}

			LoginResponseVo loginResponseVo = LoginResponseVo.success();

			return this.converterWsResponse(loginResponseVo);
		}catch (Exception e){
			e.printStackTrace();
			throw  new SystemRuntimeException(SysResultCodeEnum.SYS_TOKEN_NULL);
		}

	}



	/**
	 * 初始化绑定或者解绑群组;
	 */
//	public void initGroup(ChannelContext imChannelContext , User user)throws ImException{
//		String userId = user.getUserId();
//		List<Group> groups = user.getGroups();
//		if(CollectionUtils.isEmpty(groups)){
//			return;
//		}
//		ImServerConfig imServerConfig = ImConfig.Global.get();
//		boolean isStore = ImServerConfig.ON.equals(imServerConfig.getIsStore());
//		MessageHelper messageHelper = imServerConfig.getMessageHelper();
//		List<String> groupIds = null;
//		if(isStore){
//			groupIds = messageHelper.getGroups(userId);
//		}
//		//绑定群组
//		for(Group group : groups){
//			if(isStore && CollectionUtils.isNotEmpty(groupIds)){
//				groupIds.remove(group.getGroupId());
//			}
//			ImPacket groupPacket = new ImPacket(Command.COMMAND_JOIN_GROUP_REQ,JsonKit.toJsonBytes(group));
//			try {
//				JoinGroupReqHandler joinGroupReqHandler = CommandManager.getCommand(Command.COMMAND_JOIN_GROUP_REQ, JoinGroupReqHandler.class);
//				joinGroupReqHandler.handler(groupPacket, imChannelContext);
//			} catch (Exception e) {
//				log.error(e.toString(),e);
//			}
//		}
//		if(isStore && groupIds != null){
//			for(String groupId : groupIds){
//				messageHelper.getBindListener().onAfterGroupUnbind(imChannelContext, Group.newBuilder().groupId(groupId).build());
//			}
//		}
//	}


}
